package com.haonan.springboot_exercise.controller;

import com.haonan.springboot_exercise.bean.User;
import com.haonan.springboot_exercise.bean.pojo.JwtToken;
import com.haonan.springboot_exercise.bean.pojo.Result;
import com.haonan.springboot_exercise.dao.UserDao;
import com.haonan.springboot_exercise.service.LoginService;
import com.haonan.springboot_exercise.util.RedisUtil;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import static com.haonan.springboot_exercise.util.SmsCode.getSms;

@RestController
@CrossOrigin(origins = "http://localhost:9527",maxAge = 1800)//解决跨域问题
public class LoginController {
    @Autowired
    UserDao userDao;
    @Autowired
    LoginService loginService;
    @Autowired
    RedisUtil redisUtil;
    /**
     * 登录方法
     * @param user
     * @return Result状态码
     */
    @RequestMapping("/user/login")
    public Result login(@RequestBody User user) throws Exception {
        return this.loginService.login(user);
    }
    /**
     * 验证token是否合法性和有效性，返回用户信息。
     * 有以下几种情况：token过期、用户被禁用、还有smtp和pop服务是否被禁用
     */
    @RequestMapping("/user/info")
    public Result info(@RequestParam("token") String token) throws Exception {
        return this.loginService.info(token);
    }
    /**
     * 退出登陆，不需要任何信息就可以退出
     */
    @RequestMapping("/user/logout")
    public Result logout() throws Exception {
        return this.loginService.logout();
    }

    /**
     * 注册接口
     * @param user_name 用户名(不带@996.com)
     * @param user_password 密码
     * @return
     */
    @RequestMapping("/user/enroll")
    public Result enroll(@RequestParam("user_name") String user_name, @RequestParam("user_password") String user_password){
        if(userDao.userExists(user_name)){
            return Result.fail("用户名已存在");
        }
        userDao.enroll(user_name, user_password);
        return Result.succ(userDao.getUserByMessage(user_name, user_password));
    }

    /**
     * 用户 修改密码
     * @param user_name 用户名
     * @param old_user_password 旧密码
     * @param new_user_password 新密码
     * @return
     */
    @RequestMapping("/user/changePassword")
    public Result changePassword(@RequestParam("user_name")String user_name, @RequestParam("old_user_password") String old_user_password, @RequestParam("new_user_password")String new_user_password){
        if(!userDao.judgeUser(user_name, old_user_password)){
            return Result.fail("用户名或密码错误");
        }
        userDao.changePassword(user_name, old_user_password, new_user_password);
        return Result.succ(userDao.getUserByMessage(user_name,new_user_password));
    }
}
